package com.grow.greenhouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.grow.greenhouse.common.ErrorCode;
import com.grow.greenhouse.domain.Systemthreshold;
import com.grow.greenhouse.domain.User;
import com.grow.greenhouse.domain.Userthreshold;
import com.grow.greenhouse.domain.request.DailyNumRequest;
import com.grow.greenhouse.domain.request.UpdateAllThresholdRequest;
import com.grow.greenhouse.domain.request.UpdateOneThresholdRequest;
import com.grow.greenhouse.exception.BusinessException;
import com.grow.greenhouse.service.SystemthreholdService;
import com.grow.greenhouse.service.UserService;
import com.grow.greenhouse.service.UserthreholdService;
import com.grow.greenhouse.mapper.UserthresholdMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* @author 23854
* @description 针对表【userthrehold(用户设置数据阈值)】的数据库操作Service实现
* @createDate 2024-01-29 12:34:47
*/
@Service
public class UserthresholdServiceImpl extends ServiceImpl<UserthresholdMapper, Userthreshold>
    implements UserthreholdService{
    private final Map<String,String> translateMap = Stream.of(new String[][]{
            {"空气湿度", "airMoisture"},
            {"光照强度", "illumination"},
            {"空气温度", "airTemp"},
            {"土壤PH值", "PHvalue"},
            {"二氧化碳", "carbonDioxide"},
            {"土壤温度", "soilTemp"},
            {"土壤湿度", "soilMoisture"}
    }).collect(Collectors.toMap(data -> data[0], data -> data[1]));

    @Resource
    private UserService userService;

    @Resource
    private Gson gson;

    @Resource
    private SystemthreholdService systemthreholdService;

    @Override
    public Map<String,String> getOneThreshold(DailyNumRequest dailyNumRequest, HttpServletRequest request) {
        Map<String,String> thresholdMap = new HashMap<>();
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        String indicatorName = dailyNumRequest.getIndicatorName();

        String shedName = dailyNumRequest.getShedName();
        QueryWrapper<Userthreshold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("shedName",shedName);
        String indicator = translateMap.get(indicatorName);
        thresholdMap.put("name",indicatorName);
        Userthreshold userthreshold = this.getOne(queryWrapper);
        List<Double> numList = new ArrayList<>();
        //如果当前用户尚无用户阈值，则从系统阈值中查出来给他
        if(userthreshold == null)
        {
            QueryWrapper<Systemthreshold> systemthreholdQueryWrapper = new QueryWrapper<>();
            systemthreholdQueryWrapper.eq("shedName",shedName);
            Systemthreshold systemthreshold = systemthreholdService.getOne(systemthreholdQueryWrapper);
            Userthreshold newUserThreshold = new Userthreshold();
            BeanUtils.copyProperties(systemthreshold,newUserThreshold);
            newUserThreshold.setShedName(systemthreshold.getCropName()+"棚");
            newUserThreshold.setUserId(userId);
            this.save(newUserThreshold);
            String thresholdJson = newUserThreshold.getUserthreholdByIndicator(indicator);
            numList = gson.fromJson(thresholdJson, new TypeToken<List<Double>>() {
            }.getType());
        }
        //如果当前用户已有用户阈值，则直接返回
        else{
            String thresholdJson = userthreshold.getUserthreholdByIndicator(indicator);
            numList = gson.fromJson(thresholdJson, new TypeToken<List<Double>>() {
            }.getType());
        }
        thresholdMap.put("max",numList.get(2).toString());
        thresholdMap.put("min",numList.get(0).toString());
        return thresholdMap;
    }

    @Override
    public List<Map<String,String>> getAllThreshold(String shedName, HttpServletRequest request) {
        List<Map<String,String>> thresHoldList = new ArrayList<>();
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        QueryWrapper<Userthreshold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("shedName",shedName);
        Userthreshold userthreshold = this.getOne(queryWrapper);
        translateMap.forEach((key,value)->{
            Map<String,String> thresholdMap = new HashMap<>();
            String valueNumJson = userthreshold.getUserthreholdByIndicator(value);
            List<String> valueNumList = gson.fromJson(valueNumJson, new TypeToken<List<String>>() {
            }.getType());
            thresholdMap.put("min",valueNumList.get(0));
            thresholdMap.put("max",valueNumList.get(2));
            thresholdMap.put("name",key);
            thresHoldList.add(thresholdMap);
        });
        return thresHoldList;
    }

    @Override
    public String updateThreshold(UpdateOneThresholdRequest thresholdRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        Double minValue = Double.valueOf(thresholdRequest.getMinValue());
        Double maxValue = Double.valueOf(thresholdRequest.getMaxValue());
        double suitableValue = (minValue + maxValue) / 2;
        List<String> list = Stream.of(new String[]
                {minValue.toString(), Double.toString(suitableValue),maxValue.toString()})
                .collect(Collectors.toList());
        String indicatorName = thresholdRequest.getIndicatorName();
        String shedName = thresholdRequest.getShedName();
        String json = gson.toJson(list);
        indicatorName = translateMap.get(indicatorName);
        UpdateWrapper<Userthreshold> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("userId",userId);
        updateWrapper.eq("shedName",shedName);
        updateWrapper.set(indicatorName,json);
        boolean update = this.update(updateWrapper);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"修改失败");
        }
        return "修改成功";

    }

    @Override
    public String updateAllThreshold(UpdateAllThresholdRequest thresholdRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String shedNameJson = loginUser.getShedName();
        String shedName = thresholdRequest.getShedName();
        List<String> shedNameList = gson.fromJson(shedNameJson, new TypeToken<List<String>>() {
        }.getType());
        if(!shedNameList.contains(shedName)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户没有此大棚");
        }
        //多次调用修改单阈值即可完成全修改
        thresholdRequest.getThresholdList().forEach(
                item->{
                    UpdateOneThresholdRequest updateOneThresholdRequest = new UpdateOneThresholdRequest();
                    updateOneThresholdRequest.setMinValue(item.get("minValue"));
                    updateOneThresholdRequest.setMaxValue(item.get("maxValue"));
                    updateOneThresholdRequest.setShedName(shedName);
                    updateOneThresholdRequest.setIndicatorName(item.get("indicatorName"));
                    updateThreshold(updateOneThresholdRequest,request);
                });
        return "修改成功";
    }

    @Override
    public List<String> getSystemCropName() {

        return systemthreholdService.list()
                .stream().map(Systemthreshold::getCropName).collect(Collectors.toList());
    }
}




